package com.wavercaz.freeforum.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wavercaz.freeforum.pojo.Admin;
import com.wavercaz.freeforum.pojo.CommonSearchParam;
import com.wavercaz.freeforum.services.AdminService;
import com.wavercaz.freeforum.services.UserInfoService;
import com.wavercaz.freeforum.services.impl.NewUserDetails;
import com.wavercaz.freeforum.utils.JWTUtil;
import com.wavercaz.freeforum.utils.LoginUtil;
import com.wavercaz.freeforum.utils.QueryUtil;
import com.wavercaz.freeforum.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AdminController {
    @Autowired
    private  AdminService adminService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginUtil loginUtil;

    // 登录
    @PostMapping("/admin/login")
    public ResponseResult login(@RequestBody Map<String,String> loginForm) {
        loginUtil.setType("admin");
        Map<String,String> data=new HashMap<>();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginForm.get("username"), loginForm.get("password"));
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        Admin admin = (Admin)((NewUserDetails) authenticate.getPrincipal()).getUserDetail();
        Map<String,Object> tokenData = new HashMap<>();
        tokenData.put("id",admin.getId());
        data.put("token", JWTUtil.getToken(tokenData));
        return new ResponseResult(HttpStatus.OK.value(),"登录成功",data);
    }

    // 注册
    @PostMapping("/admin/register")
    @Transactional
    public ResponseResult register(@RequestBody Admin registerAdmin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        Admin admin = adminService.getOne(queryWrapper.eq("username", registerAdmin.getUsername()));
        if(admin!=null) {
            return new ResponseResult(HttpStatus.NO_CONTENT.value(),"该用户名已存在");
        }
        registerAdmin.setPassword(bCryptPasswordEncoder.encode(registerAdmin.getPassword()));
        registerAdmin.setNickName(registerAdmin.getUsername());
        registerAdmin.setAvatarUrl("/default/defaultUserIcon.png");
        adminService.save(registerAdmin);
        return new ResponseResult(HttpStatus.OK.value(),"新增成功");
    }

    // 注销
    @PostMapping("/admin/logout")
    public ResponseResult logout(@RequestHeader("Authorization") String token) {
        List<String> abandonTokens= (List<String>) redisTemplate.opsForValue().get("abandonTokens");
        if(abandonTokens==null){
            abandonTokens=new ArrayList<>();
        }
        //如果token黑名单有1000条，则截去一半
        if(abandonTokens.size()==1000){
            abandonTokens.subList(499,abandonTokens.size());
        }
        abandonTokens.add(token);
        redisTemplate.opsForValue().set("abandonTokens",abandonTokens);
        return new ResponseResult(HttpStatus.OK.value(),"注销成功");
    }

    // 信息
    @GetMapping("/admin/info")
    public ResponseResult getInfo(@RequestHeader("Authorization") String token) {
        Admin admin = adminService.getById(Integer.parseInt(JWTUtil.verifyToken(token).getClaim("id").asString()));
        if(admin == null) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "无此相关信息");
        else return new ResponseResult(HttpStatus.OK.value(), admin);
    }

    // 增
    @PutMapping("/admin")
    public ResponseResult save(@RequestBody Admin admin) {
        boolean result = adminService.save(admin);
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "新增失败");
        else return new ResponseResult(HttpStatus.OK.value(), "新增成功");
    }

    // 删
    @DeleteMapping("/admin")
    public ResponseResult delete(@RequestBody List<Integer> ids) {
        boolean result = adminService.removeByIds(ids);
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "删除失败");
        else return new ResponseResult(HttpStatus.OK.value(), "删除成功");
    }

    // 改
    @PostMapping("/admin")
    public ResponseResult update(@RequestBody Admin admin) {
        boolean result = adminService.updateById(admin);
        if(!result) return new ResponseResult(HttpStatus.NO_CONTENT.value(), "修改失败");
        else return new ResponseResult(HttpStatus.OK.value(), "修改成功");
    }

    // 列表
    @PostMapping("/adminList")
    public ResponseResult list(@RequestBody(required = false) CommonSearchParam commonSearchParam) {
        Object data = null;
        if(commonSearchParam != null) {
            QueryWrapper queryWrapper = QueryUtil.getQueryWrapper(commonSearchParam.getSearches());
            if(commonSearchParam.getPageNum()!=null && commonSearchParam.getPageSize()!=null)
                data= adminService.page(new Page<>(commonSearchParam.getPageNum(), commonSearchParam.getPageSize()), queryWrapper);
            else data= adminService.list(queryWrapper);
        }
        else data= adminService.list();
        return new ResponseResult(HttpStatus.OK.value(), data);
    }
}
